<template>
  <div 
    ref="chatWindowRef" 
    class="chat-window"
    :class="mobileClasses"
    :style="mobileStyles"
  >
    <!-- 聊天头部 -->
    <div class="chat-window__header">
      <div class="chat-header">
        <div class="chat-header__info">
          <div class="chat-header__avatar">
            <AvatarImage 
              :src="conversation?.avatar" 
              :alt="conversation?.title || '聊天'"
              size="medium"
            />
          </div>
          <div class="chat-header__details">
            <h3 class="chat-header__title">{{ conversation?.title || '选择聊天' }}</h3>
            <p class="chat-header__status">{{ conversationStatus }}</p>
          </div>
        </div>
        <div class="chat-header__actions">
          <button 
            class="chat-header__action"
            @click="handleMoreActions"
            title="更多操作"
          >
            <i class="el-icon-more" />
          </button>
        </div>
      </div>
    </div>

    <!-- 消息列表区域 -->
    <div 
      ref="messagesContainer"
      class="chat-window__messages"
      @scroll="handleScroll"
    >
      <!-- 下拉刷新区域 -->
      <div 
        v-if="!isLoading && messages.length > 0"
        class="pull-refresh-trigger"
        @click="handleRefreshMessages"
      >
        <button class="refresh-button">
          <i class="el-icon-refresh" />
          下拉刷新
        </button>
      </div>

      <!-- 加载更多历史消息 -->
      <div 
        v-if="hasMoreMessages && !isLoadingHistoryForCurrentConversation"
        class="load-more-trigger"
        @click="loadMoreMessages"
      >
        <button class="load-more-button">
          <i class="el-icon-arrow-up" />
          加载更多消息
        </button>
      </div>
      
      <!-- 历史消息加载中 -->
      <div v-if="isLoadingHistoryForCurrentConversation" class="loading-indicator">
        <i class="el-icon-loading" />
        <span>加载历史消息中...</span>
      </div>

      <!-- 加载失败提示 -->
      <div v-if="loadErrorForCurrentConversation" class="error-indicator">
        <div class="error-content">
          <i class="el-icon-warning" />
          <span>{{ loadErrorForCurrentConversation }}</span>
          <button 
            class="retry-button"
            @click="handleRetryLoadMessages"
            :disabled="isLoadingHistoryForCurrentConversation"
          >
            <i v-if="isLoadingHistoryForCurrentConversation" class="el-icon-loading" />
            <i v-else class="el-icon-refresh" />
            重试 ({{ retryAttemptsForCurrentConversation }}/3)
          </button>
        </div>
      </div>

      <!-- 虚拟滚动消息列表 -->
      <div class="messages-list" :style="{ height: virtualScrollState.totalHeight + 'px' }">
        <div 
          class="virtual-list-content"
          :style="{ transform: `translateY(${virtualScrollState.offsetY}px)` }"
        >
          <MessageItem
            v-for="message in virtualScrollState.visibleItems"
            :key="message.id"
            :message="message.data"
            :current-user-id="currentUser?.id"
            :show-sender-name="conversation?.type === 'GROUP'"
            @image-click="handleImageClick"
            @file-click="handleFileClick"
            @voice-click="handleVoiceClick"
            @retry-message="handleRetryMessage"
          />
        </div>
      </div>

      <!-- 空状态 -->
      <div v-if="!messages.length && !isLoading" class="empty-state">
        <div class="empty-state__icon">
          <i class="el-icon-chat-dot-round" />
        </div>
        <p class="empty-state__text">暂无消息，开始聊天吧</p>
      </div>

      <!-- 消息加载中 -->
      <div v-if="isLoading && !messages.length" class="loading-indicator">
        <i class="el-icon-loading" />
        <span>加载消息中...</span>
      </div>
    </div>

    <!-- 消息输入区域 -->
    <div class="chat-window__input">
      <div class="message-input">
        <!-- 输入工具栏 -->
        <div class="message-input__toolbar">
          <button 
            class="toolbar-button"
            @click="handleEmojiClick"
            title="表情"
          >
            <i class="el-icon-sunny" />
          </button>
          <button 
            class="toolbar-button"
            @click="handleImageUpload"
            title="图片"
          >
            <i class="el-icon-picture" />
          </button>
          <button 
            class="toolbar-button"
            @click="handleFileUpload"
            title="文件"
          >
            <i class="el-icon-folder" />
          </button>
        </div>

        <!-- 文本输入框 -->
        <div class="message-input__content">
          <textarea
            ref="messageInput"
            v-model="inputMessage"
            class="message-input__textarea"
            placeholder="输入消息..."
            rows="1"
            :disabled="!conversation || isSending"
            @keydown="handleKeyDown"
            @input="handleInput"
            @focus="handleInputFocus"
            @blur="handleInputBlur"
          />
        </div>

        <!-- 发送按钮 -->
        <div class="message-input__actions">
          <button
            class="send-button"
            :class="{ 
              'send-button--active': canSend,
              'send-button--sending': isSending
            }"
            :disabled="!canSend || isSending"
            @click="handleSendMessage"
            title="发送消息 (Enter)"
          >
            <i v-if="isSending" class="el-icon-loading" />
            <i v-else class="el-icon-position" />
          </button>
        </div>
      </div>

      <!-- 输入提示 -->
      <div v-if="inputHint" class="input-hint">
        {{ inputHint }}
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, nextTick, onMounted, onUnmounted } from 'vue'
import { useMessagesStore } from '@/stores/messages'
import { useConversationsStore } from '@/stores/conversations'
import { useAuthStore } from '@/stores/auth'
import { rsocketService } from '@/services/rsocket'
import { useMobileInteraction } from '@/composables/useMobileInteraction'
import { useVirtualScroll } from '@/composables/useVirtualScroll'
import { messageCache } from '@/utils/messageCache'
import { APP_CONSTANTS } from '@/utils/constants'
import MessageItem from './MessageItem.vue'
import AvatarImage from './AvatarImage.vue'
import type { Message, Conversation, MessageType, MessageContent, RealTimeMessage, NewMessagePush, MessageStatusPush } from '@/types'

// Props
interface Props {
  conversationId?: string
}

const props = defineProps<Props>()

// Emits
interface Emits {
  (e: 'imageClick', imageUrl: string): void
  (e: 'fileClick', fileUrl: string, fileName: string): void
  (e: 'voiceClick', voiceUrl: string): void
  (e: 'moreActions'): void
}

const emit = defineEmits<Emits>()

// Stores
const messagesStore = useMessagesStore()
const conversationsStore = useConversationsStore()
const authStore = useAuthStore()

// Refs
const messagesContainer = ref<HTMLElement>()
const messageInput = ref<HTMLTextAreaElement>()
const chatWindowRef = ref<HTMLElement>()

// Mobile interaction composable
const mobileInteraction = useMobileInteraction(chatWindowRef, {
  enableSwipeGestures: true,
  enableVirtualKeyboard: true,
  optimizeTouchTargets: true,
  enableHapticFeedback: true,
  swipeThreshold: 30,
  touchTargetMinSize: 44
})

const {
  isMobile,
  isMobileDevice,
  shouldOptimizeForTouch,
  isKeyboardVisible,
  keyboardHeight,
  keyboardAdjustment,
  onSwipe,
  handleInputFocus: mobileHandleInputFocus,
  optimizeTouchTarget,
  preventInputZoom,
  optimizeScrolling
} = mobileInteraction

// Reactive state
const inputMessage = ref('')
const isSending = ref(false)
const inputHint = ref('')
const defaultAvatar = APP_CONSTANTS.DEFAULT_AVATAR
const autoScrollEnabled = ref(true)
const lastScrollTop = ref(0)
const messageSubscription = ref<(() => void) | null>(null)
const processedMessageIds = ref(new Set<string>())

// Computed properties
const currentUser = computed(() => authStore.currentUser)

const conversation = computed(() => {
  if (!props.conversationId) return null
  return conversationsStore.getConversationById(props.conversationId)
})

const messages = computed(() => {
  if (!props.conversationId) return []
  return messagesStore.getMessagesByConversation(props.conversationId)
})

// Transform messages for virtual scrolling
const virtualScrollItems = computed(() => {
  return messages.value.map(message => ({
    id: message.messageId,
    data: message,
    height: 80 // Estimated height, will be updated dynamically
  }))
})

// Virtual scroll state
const virtualScrollState = ref({
  startIndex: 0,
  endIndex: 0,
  offsetY: 0,
  totalHeight: 0,
  visibleItems: []
})

// Simple virtual scrolling implementation
const updateVirtualScrollState = () => {
  if (!messagesContainer.value) return
  
  const containerHeight = messagesContainer.value.clientHeight
  const scrollTop = messagesContainer.value.scrollTop
  const itemHeight = 80
  const overscan = 3
  
  const startIndex = Math.max(0, Math.floor(scrollTop / itemHeight) - overscan)
  const visibleCount = Math.ceil(containerHeight / itemHeight)
  const endIndex = Math.min(virtualScrollItems.value.length - 1, startIndex + visibleCount + overscan * 2)
  
  const offsetY = startIndex * itemHeight
  const totalHeight = virtualScrollItems.value.length * itemHeight
  const visibleItems = virtualScrollItems.value.slice(startIndex, endIndex + 1)
  
  virtualScrollState.value = {
    startIndex,
    endIndex,
    offsetY,
    totalHeight,
    visibleItems
  }
}

const isLoading = computed(() => messagesStore.isLoading)

const hasMoreMessages = computed(() => {
  if (!props.conversationId) return false
  return messagesStore.hasMoreMessagesForConversation(props.conversationId)
})

const isLoadingHistoryForCurrentConversation = computed(() => {
  if (!props.conversationId) return false
  return messagesStore.isLoadingHistoryForConversation(props.conversationId)
})

const loadErrorForCurrentConversation = computed(() => {
  if (!props.conversationId) return null
  return messagesStore.getLoadErrorForConversation(props.conversationId)
})

const retryAttemptsForCurrentConversation = computed(() => {
  if (!props.conversationId) return 0
  return messagesStore.getRetryAttemptsForConversation(props.conversationId)
})

const canSend = computed(() => {
  return inputMessage.value.trim().length > 0 && 
         !!conversation.value && 
         !isSending.value
})

const conversationStatus = computed(() => {
  if (!conversation.value) return ''
  
  if (conversation.value.type === 'GROUP') {
    return `${conversation.value.participants.length} 人`
  }
  
  // For private conversations, show online status
  // This would need to be implemented with friend status
  return '在线' // Placeholder
})

// Mobile-specific computed properties
const mobileClasses = computed(() => {
  return {
    'mobile-optimized': isMobileDevice.value,
    'touch-optimized': shouldOptimizeForTouch.value,
    'keyboard-visible': isKeyboardVisible?.value,
    'mobile-layout': isMobile.value
  }
})

const mobileStyles = computed(() => {
  const styles: Record<string, string> = {}
  
  // Adjust input area for virtual keyboard
  if (isKeyboardVisible?.value && keyboardAdjustment.value > 0) {
    styles['--keyboard-height'] = `${keyboardAdjustment.value}px`
  }
  
  return styles
})

// Methods
const loadMessages = async (page = 1) => {
  if (!props.conversationId) return
  
  try {
    await messagesStore.loadMessages({
      conversationId: props.conversationId,
      page,
      pageSize: 20
    })
    
    // Auto scroll to bottom on first load
    if (page === 1) {
      await nextTick()
      scrollToBottom()
    }
  } catch (error) {
    console.error('Failed to load messages:', error)
  }
}

const loadMoreMessages = async () => {
  if (!props.conversationId || !hasMoreMessages.value) return
  
  try {
    await messagesStore.loadMoreHistory(props.conversationId)
  } catch (error) {
    console.error('Failed to load more messages:', error)
  }
}

const handleRefreshMessages = async () => {
  if (!props.conversationId) return
  
  try {
    await messagesStore.refreshMessages(props.conversationId)
    await nextTick()
    scrollToBottom()
  } catch (error) {
    console.error('Failed to refresh messages:', error)
  }
}

const handleRetryLoadMessages = async () => {
  if (!props.conversationId) return
  
  try {
    await messagesStore.retryLoadMessages(props.conversationId)
  } catch (error) {
    console.error('Failed to retry load messages:', error)
  }
}

const handleSendMessage = async () => {
  if (!canSend.value || !props.conversationId) return
  
  const messageText = inputMessage.value.trim()
  if (!messageText) return
  
  try {
    isSending.value = true
    inputHint.value = '发送中...'
    
    const content: MessageContent = { text: messageText }
    
    await messagesStore.sendMessage({
      conversationId: props.conversationId,
      messageType: 'TEXT',
      content
    })
    
    // Clear input and scroll to bottom
    inputMessage.value = ''
    inputHint.value = ''
    await nextTick()
    scrollToBottom()
    
    // Focus back to input
    messageInput.value?.focus()
  } catch (error) {
    console.error('Failed to send message:', error)
    inputHint.value = '发送失败，请重试'
    setTimeout(() => {
      inputHint.value = ''
    }, 3000)
  } finally {
    isSending.value = false
  }
}

const handleKeyDown = (event: KeyboardEvent) => {
  if (event.key === 'Enter') {
    if (event.shiftKey) {
      // Shift + Enter: new line
      return
    } else {
      // Enter: send message
      event.preventDefault()
      handleSendMessage()
    }
  }
}

const handleInput = () => {
  // Auto-resize textarea
  if (messageInput.value) {
    messageInput.value.style.height = 'auto'
    messageInput.value.style.height = `${messageInput.value.scrollHeight}px`
  }
  
  // Clear hint when user starts typing
  if (inputHint.value && inputMessage.value.trim()) {
    inputHint.value = ''
  }
}

const handleInputFocus = () => {
  // Mark conversation as read when user focuses input
  if (props.conversationId) {
    conversationsStore.markConversationAsRead(props.conversationId)
  }
}

const handleInputBlur = () => {
  // Could implement typing status here
}

const handleScroll = (event: Event) => {
  if (!messagesContainer.value) return
  
  const { scrollTop, scrollHeight, clientHeight } = messagesContainer.value
  
  // Handle virtual scrolling
  updateVirtualScrollState()
  
  // Check if user scrolled to top (load more messages)
  if (scrollTop === 0 && hasMoreMessages.value && !isLoadingHistoryForCurrentConversation.value) {
    loadMoreMessages()
  }
  
  // Check if user is at bottom (enable auto-scroll)
  const isAtBottom = scrollHeight - scrollTop - clientHeight < 50
  autoScrollEnabled.value = isAtBottom
  
  lastScrollTop.value = scrollTop
}

const scrollToBottom = (smooth = false) => {
  if (!messagesContainer.value) return
  
  try {
    const scrollOptions: ScrollToOptions = {
      top: messagesContainer.value.scrollHeight,
      behavior: smooth ? 'smooth' : 'auto'
    }
    
    if (messagesContainer.value.scrollTo) {
      messagesContainer.value.scrollTo(scrollOptions)
    } else {
      // Fallback for test environments
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
    }
  } catch (error) {
    // Silently handle scroll errors in test environments
    console.warn('Scroll error:', error)
  }
}

const handleRetryMessage = async (message: Message) => {
  try {
    await messagesStore.retryFailedMessage(message.messageId)
  } catch (error) {
    console.error('Failed to retry message:', error)
  }
}

const handleImageClick = (imageUrl: string) => {
  emit('imageClick', imageUrl)
}

const handleFileClick = (fileUrl: string, fileName: string) => {
  emit('fileClick', fileUrl, fileName)
}

const handleVoiceClick = (voiceUrl: string) => {
  emit('voiceClick', voiceUrl)
}

const handleMoreActions = () => {
  emit('moreActions')
}



// Placeholder handlers for toolbar buttons
const handleEmojiClick = () => {
  // TODO: Implement emoji picker
  console.log('Emoji picker not implemented yet')
}

const handleImageUpload = () => {
  // TODO: Implement image upload
  console.log('Image upload not implemented yet')
}

const handleFileUpload = () => {
  // TODO: Implement file upload
  console.log('File upload not implemented yet')
}

// Real-time message handling functions
const setupMessageSubscription = () => {
  if (messageSubscription.value) {
    messageSubscription.value()
  }

  messageSubscription.value = rsocketService.addMessageSubscriber({
    onMessage: handleRealTimeMessage,
    onError: (error) => {
      console.error('Real-time message subscription error:', error)
    }
  })
}

const handleRealTimeMessage = (realTimeMessage: RealTimeMessage) => {
  try {
    switch (realTimeMessage.type) {
      case 'NEW_MESSAGE':
        handleNewMessagePush(realTimeMessage.data as NewMessagePush)
        break
      case 'MESSAGE_READ':
      case 'MESSAGE_DELIVERED':
        handleMessageStatusPush(realTimeMessage.data as MessageStatusPush)
        break
      case 'USER_ONLINE':
      case 'USER_OFFLINE':
        // Handle user status updates if needed
        break
      case 'TYPING_START':
      case 'TYPING_END':
        // Handle typing status if needed
        break
      default:
        console.log('Unhandled real-time message type:', realTimeMessage.type)
    }
  } catch (error) {
    console.error('Error handling real-time message:', error)
  }
}

const handleNewMessagePush = (pushData: NewMessagePush) => {
  const { message, conversation } = pushData
  
  // Check for message deduplication
  if (processedMessageIds.value.has(message.messageId)) {
    return
  }
  
  // Add to processed messages set
  processedMessageIds.value.add(message.messageId)
  
  // Add message to store with deduplication and sorting
  messagesStore.addMessage(message)
  
  // Update conversation with new message
  conversationsStore.updateLastMessage(conversation.id, message)
  
  // Auto-mark as read if this is the current conversation and user is focused
  if (message.conversationId === props.conversationId && 
      message.fromUserId !== currentUser.value?.id &&
      document.hasFocus() && 
      autoScrollEnabled.value) {
    markMessageAsReadDelayed(message.messageId, message.conversationId)
  }
  
  // Auto-scroll to bottom if enabled
  if (autoScrollEnabled.value && message.conversationId === props.conversationId) {
    nextTick(() => {
      scrollToBottom(true)
    })
  }
}

const handleMessageStatusPush = (statusData: MessageStatusPush) => {
  // Update message status in store
  messagesStore.updateMessageStatus(statusData.messageId, statusData.status)
}

const markMessageAsReadDelayed = (messageId: string, conversationId: string) => {
  // Delay marking as read to ensure user has seen the message
  setTimeout(async () => {
    try {
      await messagesStore.markMessageAsRead({ messageId, conversationId })
      
      // Also send read status via RSocket
      if (rsocketService.isConnected()) {
        await rsocketService.markMessageAsRead(messageId, conversationId)
      }
    } catch (error) {
      console.error('Failed to mark message as read:', error)
    }
  }, 1000) // 1 second delay
}

const cleanupProcessedMessages = () => {
  // Keep only recent message IDs to prevent memory leak
  const maxProcessedMessages = 1000
  if (processedMessageIds.value.size > maxProcessedMessages) {
    const idsArray = Array.from(processedMessageIds.value)
    const toKeep = idsArray.slice(-maxProcessedMessages / 2)
    processedMessageIds.value = new Set(toKeep)
  }
}

// Watch for conversation changes
watch(() => props.conversationId, async (newConversationId) => {
  if (newConversationId) {
    // Set current conversation
    conversationsStore.setCurrentConversation(newConversationId)
    
    // Load messages
    await loadMessages()
    
    // Focus input
    await nextTick()
    messageInput.value?.focus()
  }
}, { immediate: true })

// Watch for new messages to auto-scroll
watch(messages, async () => {
  if (autoScrollEnabled.value) {
    await nextTick()
    scrollToBottom(true)
  }
}, { deep: true })

// Watch for virtual scroll items changes
watch(virtualScrollItems, () => {
  updateVirtualScrollState()
}, { deep: true })

// Mobile interaction setup
const setupMobileOptimizations = () => {
  if (!chatWindowRef.value) return

  // Optimize touch targets for mobile
  const optimizeElements = () => {
    if (!shouldOptimizeForTouch.value) return

    // Optimize buttons
    const buttons = chatWindowRef.value?.querySelectorAll('button, .toolbar-button, .send-button')
    buttons?.forEach((button) => {
      optimizeTouchTarget(button as HTMLElement, {
        minSize: 44,
        hapticFeedback: true,
        preventDoubleClick: true
      })
    })
  }

  // Setup scrolling optimization
  const optimizeScrollElements = () => {
    if (messagesContainer.value) {
      optimizeScrolling(messagesContainer.value)
    }
  }

  // Prevent input zoom on iOS
  const setupInputOptimization = () => {
    if (messageInput.value && isMobileDevice.value) {
      preventInputZoom(messageInput.value)
    }
  }

  // Setup mobile input focus handling
  const setupMobileInputFocus = () => {
    if (!messageInput.value || !isMobileDevice.value) return

    const originalHandleInputFocus = handleInputFocus
    const enhancedHandleInputFocus = () => {
      originalHandleInputFocus()
      
      // Use mobile-specific input focus handling
      if (mobileHandleInputFocus && chatWindowRef.value) {
        mobileHandleInputFocus(messageInput.value!, {
          scrollIntoView: true,
          adjustContainer: chatWindowRef.value
        })
      }
    }

    // Replace the original focus handler
    if (messageInput.value) {
      messageInput.value.removeEventListener('focus', handleInputFocus)
      messageInput.value.addEventListener('focus', enhancedHandleInputFocus)
    }
  }

  // Apply optimizations
  setTimeout(() => {
    optimizeElements()
    optimizeScrollElements()
    setupInputOptimization()
    setupMobileInputFocus()
  }, 100)

  return () => {
    // Cleanup function
  }
}

// Lifecycle
onMounted(() => {
  // Focus input on mount
  messageInput.value?.focus()
  
  // Setup real-time message subscription
  setupMessageSubscription()
  
  // Setup mobile optimizations
  const cleanupMobileOptimizations = setupMobileOptimizations()
  
  // Setup periodic cleanup of processed messages
  const cleanupInterval = setInterval(cleanupProcessedMessages, 60000) // Every minute
  
  // Store cleanup function for unmount
  onUnmounted(() => {
    clearInterval(cleanupInterval)
    cleanupMobileOptimizations?.()
  })
})

onUnmounted(() => {
  // Clear current conversation
  conversationsStore.setCurrentConversation(null)
  
  // Clean up message subscription
  if (messageSubscription.value) {
    messageSubscription.value()
    messageSubscription.value = null
  }
  
  // Clear processed messages
  processedMessageIds.value.clear()
})
</script>

<style lang="scss" scoped>
.chat-window {
  display: flex;
  flex-direction: column;
  height: 100%;
  background: #fff;

  &__header {
    flex-shrink: 0;
    border-bottom: 1px solid #e5e5e5;
    background: #fff;
    z-index: 10;
  }

  &__messages {
    flex: 1;
    overflow-y: auto;
    padding: 16px 0;
    background: #f8f9fa;
  }

  &__input {
    flex-shrink: 0;
    border-top: 1px solid #e5e5e5;
    background: #fff;
  }
}

.chat-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  height: 60px;

  &__info {
    display: flex;
    align-items: center;
    flex: 1;
    min-width: 0;
  }

  &__avatar {
    width: 40px;
    height: 40px;
    margin-right: 12px;
    flex-shrink: 0;

    img {
      width: 100%;
      height: 100%;
      border-radius: 50%;
      object-fit: cover;
    }
  }

  &__details {
    flex: 1;
    min-width: 0;
  }

  &__title {
    font-size: 16px;
    font-weight: 600;
    color: #333;
    margin: 0 0 2px 0;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  &__status {
    font-size: 12px;
    color: #999;
    margin: 0;
  }

  &__actions {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  &__action {
    width: 32px;
    height: 32px;
    border: none;
    background: transparent;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    color: #666;
    transition: all 0.2s;

    &:hover {
      background: #f5f5f5;
      color: #333;
    }
  }
}

.pull-refresh-trigger {
  text-align: center;
  padding: 8px 16px;
  border-bottom: 1px solid #f0f0f0;
}

.refresh-button {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  padding: 6px 12px;
  border: 1px solid #e0e0e0;
  background: #f8f9fa;
  border-radius: 16px;
  font-size: 11px;
  color: #666;
  cursor: pointer;
  transition: all 0.2s;

  &:hover {
    background: #e9ecef;
    border-color: #d0d0d0;
  }

  i {
    font-size: 12px;
  }
}

.load-more-trigger {
  text-align: center;
  padding: 16px;
}

.load-more-button {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  border: 1px solid #ddd;
  background: #fff;
  border-radius: 20px;
  font-size: 12px;
  color: #666;
  cursor: pointer;
  transition: all 0.2s;

  &:hover {
    background: #f5f5f5;
    border-color: #ccc;
  }
}

.error-indicator {
  padding: 12px 16px;
  background: #fff3cd;
  border: 1px solid #ffeaa7;
  border-radius: 8px;
  margin: 8px 16px;
}

.error-content {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 12px;
  color: #856404;

  .el-icon-warning {
    color: #f39c12;
    font-size: 14px;
  }

  span {
    flex: 1;
    min-width: 0;
  }
}

.retry-button {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  padding: 4px 8px;
  border: 1px solid #f39c12;
  background: #fff;
  border-radius: 12px;
  font-size: 11px;
  color: #f39c12;
  cursor: pointer;
  transition: all 0.2s;
  white-space: nowrap;

  &:hover:not(:disabled) {
    background: #f39c12;
    color: #fff;
  }

  &:disabled {
    opacity: 0.6;
    cursor: not-allowed;
  }

  .el-icon-loading {
    animation: spin 1s linear infinite;
  }
}

.loading-indicator {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 16px;
  color: #999;
  font-size: 14px;

  .el-icon-loading {
    animation: spin 1s linear infinite;
  }
}

.messages-list {
  min-height: 100px;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: #999;

  &__icon {
    font-size: 48px;
    margin-bottom: 16px;
    opacity: 0.5;
  }

  &__text {
    font-size: 14px;
    margin: 0;
  }
}

.message-input {
  display: flex;
  align-items: flex-end;
  padding: 12px 16px;
  gap: 12px;

  &__toolbar {
    display: flex;
    align-items: center;
    gap: 4px;
    flex-shrink: 0;
  }

  &__content {
    flex: 1;
    min-width: 0;
  }

  &__textarea {
    width: 100%;
    min-height: 36px;
    max-height: 120px;
    padding: 8px 12px;
    border: 1px solid #ddd;
    border-radius: 18px;
    font-size: 14px;
    line-height: 1.4;
    resize: none;
    outline: none;
    background: #f8f9fa;
    transition: all 0.2s;

    &:focus {
      border-color: #007aff;
      background: #fff;
    }

    &:disabled {
      background: #f5f5f5;
      color: #999;
      cursor: not-allowed;
    }

    &::placeholder {
      color: #999;
    }
  }

  &__actions {
    flex-shrink: 0;
  }
}

.toolbar-button {
  width: 32px;
  height: 32px;
  border: none;
  background: transparent;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: #666;
  font-size: 16px;
  transition: all 0.2s;

  &:hover {
    background: #f5f5f5;
    color: #333;
  }
}

.send-button {
  width: 36px;
  height: 36px;
  border: none;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 16px;
  transition: all 0.2s;
  background: #ddd;
  color: #999;

  &--active {
    background: #007aff;
    color: white;

    &:hover {
      background: #0056cc;
    }
  }

  &--sending {
    background: #007aff;
    color: white;
    cursor: not-allowed;

    .el-icon-loading {
      animation: spin 1s linear infinite;
    }
  }

  &:disabled {
    cursor: not-allowed;
    opacity: 0.6;
  }
}

.input-hint {
  padding: 4px 16px 8px;
  font-size: 12px;
  color: #999;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

// Mobile-specific optimizations
.mobile-optimized {
  // Optimize for mobile devices
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  
  // Improve text rendering on mobile
  text-rendering: optimizeLegibility;
}

.touch-optimized {
  // Optimize touch interactions
  -webkit-touch-callout: none;
  -webkit-tap-highlight-color: transparent;
  -webkit-user-select: none;
  user-select: none;
  
  // Improve scrolling performance
  -webkit-overflow-scrolling: touch;
  overscroll-behavior: contain;
  
  // Prevent zoom on double tap
  touch-action: manipulation;
  
  // Smooth scrolling
  scroll-behavior: smooth;
  
  // Optimize button touch targets
  button, .toolbar-button, .send-button {
    min-height: 44px;
    min-width: 44px;
    position: relative;
    
    // Add touch feedback
    &:active {
      transform: scale(0.95);
      transition: transform 0.1s ease;
    }
    
    // Expand touch area for small buttons
    &::before {
      content: '';
      position: absolute;
      top: -8px;
      left: -8px;
      right: -8px;
      bottom: -8px;
      z-index: -1;
    }
  }
  
  // Optimize scrollable areas
  .chat-window__messages {
    -webkit-overflow-scrolling: touch;
    overscroll-behavior: contain;
    scroll-behavior: smooth;
  }
}

// Virtual keyboard adjustments
.keyboard-visible {
  .chat-window__input {
    padding-bottom: var(--keyboard-height, 0px);
    transition: padding-bottom 0.3s ease;
  }
  
  .message-input {
    &__textarea {
      // Ensure input stays visible when keyboard appears
      transform: translateY(0);
      transition: transform 0.3s ease;
    }
  }
}

// Mobile layout adjustments
.mobile-layout {
  .chat-header {
    // Optimize header for mobile
    &__title {
      font-size: 16px;
      font-weight: 500;
    }
    
    &__status {
      font-size: 12px;
    }
  }
  
  .message-input {
    // Optimize input area for mobile
    padding: 12px 16px;
    
    &__textarea {
      font-size: 16px; // Prevent zoom on iOS
      min-height: 40px;
      padding: 10px 14px;
    }
  }
  
  .toolbar-button {
    width: 40px;
    height: 40px;
    font-size: 18px;
  }
  
  .send-button {
    width: 40px;
    height: 40px;
    font-size: 18px;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .chat-header {
    padding: 8px 12px;
    height: 56px;

    &__avatar {
      width: 36px;
      height: 36px;
      margin-right: 10px;
    }

    &__title {
      font-size: 15px;
    }

    &__status {
      font-size: 11px;
    }
  }

  .chat-window__messages {
    padding: 12px 0;
  }

  .message-input {
    padding: 8px 12px;
    gap: 8px;

    &__textarea {
      font-size: 16px; // Prevent zoom on iOS
    }
  }

  .toolbar-button {
    width: 28px;
    height: 28px;
    font-size: 14px;
  }

  .send-button {
    width: 32px;
    height: 32px;
    font-size: 14px;
  }
}

// Orientation-specific styles
@media screen and (orientation: landscape) {
  .mobile-layout {
    .chat-header {
      height: 48px;
      padding: 6px 12px;
      
      &__avatar {
        width: 32px;
        height: 32px;
      }
      
      &__title {
        font-size: 14px;
      }
      
      &__status {
        font-size: 11px;
      }
    }
    
    .message-input {
      padding: 8px 12px;
      
      &__textarea {
        min-height: 36px;
        padding: 8px 12px;
      }
    }
    
    .toolbar-button {
      width: 36px;
      height: 36px;
      font-size: 16px;
    }
    
    .send-button {
      width: 36px;
      height: 36px;
      font-size: 16px;
    }
  }
}

// High DPI display optimizations
@media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi) {
  .touch-optimized {
    // Sharper borders on high DPI displays
    .chat-window__header, .chat-window__input {
      border-width: 0.5px;
    }
  }
}
</style>